package com.itclass.auth.authentication.adapter;

import lombok.Getter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RequestMatcherAdapter implements RequestMatcher {
    private final Log logger = LogFactory.getLog(getClass());

    @Getter
    private  List<RequestMatcher> requestMatchers = new ArrayList<>();

    public RequestMatcherAdapter() {

    }


    public RequestMatcherAdapter(List<RequestMatcher> requestMatchers) {
        Assert.notEmpty(requestMatchers, "requestMatchers must contain a value");
        Assert.noNullElements(requestMatchers, "requestMatchers cannot contain null values");
        this.requestMatchers = requestMatchers;
    }

    /**
     * Creates a new instance
     * @param requestMatchers the {@link RequestMatcher} instances to try
     */
    public RequestMatcherAdapter(RequestMatcher... requestMatchers) {
        this(Arrays.asList(requestMatchers));
    }

    public void setRequestMatchers(List<RequestMatcher> requestMatchers) {
        this.requestMatchers = requestMatchers;
    }

    public void addRequestMatchers(RequestMatcher requestMatcher) {
        this.requestMatchers.add(requestMatcher);
    }

    @Override
    public boolean matches(HttpServletRequest request) {
        for (RequestMatcher matcher : this.requestMatchers) {
            if (matcher.matches(request)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public String toString() {
        return "And " + this.requestMatchers;
    }

}
